const myRedis = require("./redis");
class Common {
  toJson(value) {
    if (value instanceof Object) {
      return JSON.stringify(value);
    } else {
      return value;
    }
  }

  toObj(value) {
    try {
      return JSON.parse(value);
    } catch (error) {
      return value;
    }
  }

  findAll(listName) {
    return new Promise((resolve, reject) => {
      myRedis.lrange(listName, 0, -1, (err, res) => {
        if (err) {
          reject(err);
        } else {
          res = res.map((item) => {
            return this.toObj(item);
          });
          resolve(res);
        }
      });
    });
  }

  getIndex(list, key, value) {
    return list.findIndex((item) => item[key] === value);
  }

  handleSuccess(query, data, msg) {
    if (Array.isArray(data)) {
      data = data.map((item) => {
        return this.toObj(item);
      });
    } else {
      data = this.toObj(data);
    }

    return this.toJson({
      code: 200,
      insName: query.insName,
      query,
      data,
      msg: msg | "success",
    });
  }

  handleError(query, error) { 
    return this.toJson({
      code: 500,
      insName: query.insName,
      query,
      msg: error.message || "error",
    });
  }
}

module.exports = Common;
